package initialize

import (
	"gin-web/app/dao"
	"gin-web/config"
	"gin-web/library/global"
	"github.com/casbin/casbin/v2"
	gormadapter "github.com/casbin/gorm-adapter/v3"
	_ "github.com/go-sql-driver/mysql"
	"github.com/ngaut/log"
	"github.com/pkg/errors"
)

func CasbinEnforcer() {
	e, err := mysqlCasbin()
	if err != nil {
		panic(errors.Wrap(err, "initialize casbin enforcer failed"))
	}
	global.Casbin = &e
	log.Info("initialize casbin enforcer success")
}

var e *casbin.Enforcer

func mysqlCasbin() (en casbin.Enforcer, err error) {
	// Initialize a Gorm adapter and use it in a Casbin enforcer:
	// The adapter will use the MySQL database named "casbin".
	// If it doesn't exist, the adapter will create it automatically.
	// You can also use an already existing gorm instance with gormadapter.NewAdapterByDB(gormInstance)
	a, err := gormadapter.NewAdapterByDBUseTableName(dao.DB(), "", "casbin") // Your driver and data source.
	if err != nil {
		log.Fatal(err.Error())
		return
	}
	e, err = casbin.NewEnforcer(config.Cfg.System.CasbinPath, a)

	if err != nil {
		return
	}
	en = *e
	return
}